import {
  addCart,
  getCartList,
  updateCart,
  deleteCart
} from '../../api/cartApi.js'

import router from '../../router/index.js'


export default {
  namespaced: true,
  state: {
    //购物车列表
    cart_list: [],
    //总价
    total: 0,
    //全选状态
    all_checked: false
  },
  getters: {},
  mutations: {
    //当前用户购物车数据，计算总价，设置是否全选
    set_cart_list(state, value) {
      state.cart_list = value
      let flag = true
      let sum = 0
      state.cart_list.forEach(cart => {
        if (cart.cart_checked == 1) {
          sum += cart.cart_count * cart.cart_price
        } else {
          flag = false
        }
      })
      state.all_checked = flag
      state.total = sum
    }
  },
  actions: {
    //删除购物车
    delete_cart(context, value) {
      deleteCart(value.car_id).then(response => {
        if (response.data.httpcode == 200) {
          // 更新本地购物车信息
          context.state.cart_list.splice(value.index, 1);
        }
      })
    },
    // 修改购物车
    update_cart(context, value) {
      updateCart(value).then(response => {
        if (response.data.httpcode == 200) {
          //更新本地购物车列表数据cart_list
          context.state.cart_list[value.index].cart_checked = value.cart_checked
          context.commit('set_cart_list', context.state.cart_list)
        }
      })
    },
    // 查询购物车
    get_cart_list(context) {
      getCartList({}).then(response => {
        context.commit('set_cart_list', response.data.data)
      })
    },
    //添加购物车
    add_cart(context) {
      addCart({
        cart_spuid: context.rootState.product.spu.spu_id,
        cart_name: context.rootState.product.sku.sku_name,
        cart_skuid: context.rootState.product.sku.sku_id,
        cart_sku: JSON.stringify(context.rootState.product.sku_attr_list),
        cart_thumburl: context.rootState.product.spu.attrKeyList[0].attrValueList[context.rootState.product
          .ablum_index].value_images[context.rootState.product.ablum_item_index],
        cart_price: context.rootState.product.sku.sku_price,
        cart_count: context.rootState.product.buy_number,
      }).then(response => {
        //添加购物车成功
        if (response.data.httpcode == 200) {
          router.push({
            path: '/customer/cart'
          })
        } else if (response.data.httpcode == 401) {
          if (confirm(response.data.httpmessage)) {
            router.push({
              path: '/login'
            })
          }
        }
      })
    }
  },
  modules: {}
}
